package com.example.test;

import com.example.dto.Goods;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class JDBCDemo {
    public static void main(String[] args) throws Exception {
        //加载驱动
        Driver driver = new com.mysql.cj.jdbc.Driver();
        // 注册驱动
        DriverManager.registerDriver(driver);
        // 创建数据库连接
        /**
         * public static Connection getConnection(String url,String user, String password)
         * url：统一资源定位符号（用于定位连接数据库的）
         *    1.协议 jdbc:mysql:
         *    2.IP 127.0.0.1/localhost/或者其他地址
         *    3.端口号 mysql默认3306，oracle默认1521
         *    4.数据库名字 mydb
         *    5.参数：如时区等
         */
        String url = "jdbc:mysql://localhost:3306/test1?useUnicode=true;characterEncoding=utf8;serverTimezone=UTC";
        String userName = "root";
        String pwd = "root";
        Connection connection = DriverManager.getConnection(url, userName, pwd);
        // 创建SQL命令发送器Statement
        Statement statement = connection.createStatement();
        // 通过Statement发送SQL命令并得到结果
        String querySql = "select *\n" +
                "        from goods where id < 10";
        //insert delete update操作都是用statement.executeUpdate（）方法
        ResultSet resultSet = statement.executeQuery(querySql);


        //查询结果封装
        List<Goods> goodsList = new ArrayList<>();
        while (resultSet.next()){
            Integer id = resultSet.getInt("id");
            String name = resultSet.getString("name");
            String author = resultSet.getString("author");
            Goods goods = new Goods();
            goods.setName(name);
            goods.setId(id);
            goods.setAuthor(author);
            goodsList.add(goods);
        }
        System.out.println(goodsList.size());
        System.out.println(goodsList.size()>0?goodsList.get(0):null);

        // 关闭数据库资源ResultSet  Statement  Connection
        statement.close();
        connection.close();
    }
}
